package edu.sctu;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DataBase {
    public List<User> getUserList() throws SQLException {
        List<User> userList = new ArrayList<User>();

        // 3+1
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        String sql = "select * from t_users";

        try {
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/sctu_javaweb_2018?serverTimezone=UTC",
                    "root",
                    "123456"
            );
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        while(resultSet.next()){

            int id = 0;
            try {
                id = resultSet.getInt(1);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            String name = null;
            try {
                name = resultSet.getString(2);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            String password = null;
            try {
                password = resultSet.getString(3);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            // [封装]在user中
            User user = new User();
            user.setId(id);
            user.setName(name);
            user.setPassword(password);

            userList.add(user);
        }
        // 数据库 -> List

        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;
    }
}
